package cn.edu.gduf.luowowo.website.web.controller;

import cn.edu.gduf.luowowo.article.domain.Destination;
import cn.edu.gduf.luowowo.article.domain.Travel;
import cn.edu.gduf.luowowo.article.domain.TravelContent;
import cn.edu.gduf.luowowo.article.query.TravelQuery;
import cn.edu.gduf.luowowo.article.service.IDestinationService;
import cn.edu.gduf.luowowo.article.service.IStrategyDetailService;
import cn.edu.gduf.luowowo.article.service.ITravelService;
import cn.edu.gduf.luowowo.cache.service.ITravelStatisVoService;
import cn.edu.gduf.luowowo.comment.domain.TravelComment;
import cn.edu.gduf.luowowo.comment.service.ITravelCommentService;
import cn.edu.gduf.luowowo.common.exception.LogicException;
import cn.edu.gduf.luowowo.common.util.AjaxResult;
import cn.edu.gduf.luowowo.member.domain.UserInfo;
import cn.edu.gduf.luowowo.website.annotation.RequiredLogin;
import cn.edu.gduf.luowowo.website.annotation.UserParam;
import cn.edu.gduf.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelStatisVoService travelStatisVoService;

    @Value("${file.path}")
    private String filePath;

    @RequestMapping("")
    public String travel(Model model, @ModelAttribute("qo") TravelQuery qo, @UserParam UserInfo user) {
        //pageInfo 查询所有公开的并且已经发布的游记
        qo.setState(Travel.STATE_RELEASE);
        model.addAttribute("pageInfo", travelService.query(qo));
        model.addAttribute("user", user);
        //tcs 最新游记动态，查询所有游记中最新的用户评论，就获取前3个
        model.addAttribute("tcs", travelCommentService.queryByCreateTime(3));
        //sds 查询国内最火的5篇攻略明细
        model.addAttribute("sds", strategyDetailService.queryDetailUnaboardViewNumTop5());
        return "travel/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model, Long id, @UserParam UserInfo user) {
        if (id == null) {
            return travel(model, new TravelQuery(), user);
        }
        //detail 游记对象
        Travel travel = travelService.get(id);
        travel.setAuthor(user);
        //TravelContent
        travel.setTravelContent(travelService.getContent(id));
        //toast
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        if (toasts != null && toasts.size() > 0) {
            Destination dest = toasts.remove(toasts.size() - 1);
        }
        model.addAttribute("toasts", toasts);
        //model.addAttribute("dest", dest);
        //sds 相关攻略
        model.addAttribute("sds", strategyDetailService.queryDetailViewNumTop3(travel.getDest().getId()));
        //ts 相关游记
        model.addAttribute("ts", travelService.getViewNumTop3(travel.getDest().getId()));
        model.addAttribute("detail", travel);
        UserInfo author = travel.getAuthor();
        if (user != null && author != null && user.getId() == author.getId()) {
            model.addAttribute("self", user);
        }
        //查询该游记的所有评论数据
        List<TravelComment> list = travelCommentService.queryByDetailId(id);
        model.addAttribute("list", list);


        model.addAttribute("travleIds",travelStatisVoService.getTravelIds(user.getId()));

        model.addAttribute("travelVo",travelStatisVoService.getTravelStatisVoDate(id));
        return "travel/detail";
    }

    @RequestMapping("/input")
    @RequiredLogin
    public String input(Model model, Long id, @UserParam UserInfo user) {
        //dests
        model.addAttribute("dests", destinationService.getDestsByDeep(3));
        if (id != null) {
            Travel travel = travelService.get(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv", travel);

            //判断当前用户修改的是否为自己的游记
            UserInfo author = travel.getAuthor(); //这是查询出来的游记作者
            if (author != null) {
                if (author.getId() != user.getId()) {
                    throw new LogicException("非法操作，不可修改他人的游记");
                }
            } else {
                throw new LogicException("非法操作");
            }
        }
        return "travel/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiredLogin
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo user) {
        travel.setAuthor(user);
        Long travelId = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(travelId);
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    //游记新增评论
    @RequestMapping("/commentAdd")
    @RequiredLogin
    public String commentAdd(Model model, TravelComment comment, @UserParam UserInfo userInfo) {
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setCity(userInfo.getCity());
        comment.setLevel(userInfo.getLevel());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        String id = travelCommentService.saveOrUpdate(comment);
        model.addAttribute("c", travelCommentService.get(id));
        model.addAttribute("floor", travelCommentService.getCount(comment.getTravelId()));
        return "travel/commentTpl";
    }



    @RequestMapping("/favornum")
    @ResponseBody
    public Object favor(Long travelId, @UserParam UserInfo userInfo) { //sid 表示攻略id
        //用户未登录
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "登录后操作");
            result.setCode(102);
            return result;
        }
        //调用方法，与 点赞/取消点赞类似
        boolean ret =travelStatisVoService.favor(travelId, userInfo.getId());
        //攻略推荐分数 +1 或者-1
        //travelStatisVoService.addCommendScore(tid, ret ? 1 : -1);
        return new AjaxResult(ret).addData(travelStatisVoService.getTravelStatisVoDate(travelId));
    }
}
